const path = require("path");
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const { init: initDB, Counter, redis } = require("./db");

const logger = morgan("tiny");

const count = "count";

const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors());
app.use(logger);

// 首页
app.get("/", async(req, res) => {
    res.sendFile(path.join(__dirname, "index.html"));
});

// 更新计数 - MySQL
app.post("/api/mysql/count", async(req, res) => {
    const { action } = req.body;
    if (action === "inc") {
        await Counter.create();
    } else if (action === "clear") {
        await Counter.destroy({
            truncate: true,
        });
    }
    res.send({
        code: 0,
        data: await Counter.count(),
    });
});

// 获取计数 - MySQL
app.get("/api/mysql/count", async(req, res) => {
    const result = await Counter.count();
    res.send({
        code: 0,
        data: result,
    });
});

// 更新计数 - Redis
app.post("/api/redis/count", async(req, res) => {
    const { action } = req.body;
    if (action === "inc") {
        redis.incr(count).then(function(result) {
            res.send({
                code: 0,
                data: result,
            });
        });
    } else if (action === "clear") {
        redis.set(count, 0).then(function(result) {
            res.send({
                code: 0,
                data: 0,
            });
        });
    }
});

// 获取计数 - Redis
app.get("/api/redis/count", async(req, res) => {
    redis.get(count, function(result) {
        res.send({
            code: 0,
            data: result,
        });
    });
});

// 小程序调用，获取微信 Open ID
app.get("/api/wx_openid", async(req, res) => {
    if (req.headers["x-wx-source"]) {
        res.send(req.headers["x-wx-openid"]);
    }
});

const port = process.env.PORT || 80;

async function bootstrap() {
    await initDB();
    app.listen(port, () => {
        console.log("启动成功", port);
    });
}

bootstrap();